package com.ccys.app.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ccys.db.cache.SysCodeUtil;
import com.ccys.db.page.AppPageDto;
import com.ccys.app.service.MemberMoreService;
import com.ccys.common.constants.*;
import com.ccys.common.enums.CodeEnum;
import com.ccys.common.third.mailGun.MailgunUtil;
import com.ccys.common.util.*;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.CommonDto;
import com.ccys.db.dto.member.*;
import com.ccys.db.entity.*;
import com.ccys.db.mapper.*;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseSysCodeService;
import com.ccys.db.vo.app.getStarted.GetConsultProfileVo;
import com.ccys.db.vo.member.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Slf4j
@Service
public class MemberMoreServiceImpl extends BaseServiceImpl<TblMember> implements MemberMoreService {

    @Autowired(required = false)
    private TblMemberMapper memberMapper;
    private static Lock lock = new ReentrantLock();
    @Autowired(required = false)
    private BaseSysCodeService baseSysCodeService;

    @Autowired(required = false)
    private TblCountryMapper tblCountryMapper;

    @Autowired(required = false)
    private TblBookingMapper tblBookingMapper;

    @Autowired(required = false)
    private TblSpecialisationMapper tblSpecialisationMapper;
    @Autowired(required = false)
    private TblAppointmentCancellationReasonMapper appointmentCancellationReasonMapper;
    @Autowired(required = false)
    private TblBookingReminderMapper tblBookingReminderMapper;

    @Autowired(required = false)
    private TblLabResultMapper tblLabResultMapper;

    @Autowired(required = false)
    private TblMemberAllergiesMapper tblMemberAllergiesMapper;

    @Autowired(required = false)
    private TblProductMapper tblProductMapper;
    @Autowired(required = false)
    private TblMemberFamilyMapper memberFamilyMapper;

    @Autowired(required = false)
    private TblPlanBenefitMemberMapper tblPlanBenefitMemberMapper;

    @Resource
    private TblSupplierMapper tblSupplierMapper;


    @Override
    public ResponseResultApp getMemberECard(CommonDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        dto.setId(curLoginMember.getId());
        List<MemberECardVO> list = this.memberMapper.getMemberECardList(dto);
        return ResponseResultApp.success(list);
    }

    @Override
    public ResponseResultApp getAppointmentHistories(CommonDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        dto.setId(curLoginMember.getId());
        dto.setTimezone(CoreAppConstants.DEFAULT_TIMEZONE);
        AppPageDto.startPage();
        List<AppointmentHistoriesVO> list =  this.memberMapper.getAppointmentHistories(dto);
        PageInfo<AppointmentHistoriesVO> pageInfo = new PageInfo<>(list);
        AppointmentHistoriesPageVO vo = new AppointmentHistoriesPageVO();
        vo.setAppointments(list);
        vo.setTotalPage(pageInfo.getPages());
        return ResponseResultApp.success(vo);
    }

    @Override
    public ResponseResultApp getAppointmentCancellationReasons(AppointmentCancellationReasonsDto dto) {
        if(StringUtil.isEmpty(dto.getBooking_id())) {
            return ResponseResultApp.error("Booking invalid");
        }
        TblBooking tblBooking = this.tblBookingMapper.selectByPrimaryKey(dto.getBooking_id());
        if(tblBooking == null){
            return ResponseResultApp.error("Booking invalid");
        }
        dto.setClinic_id(tblBooking.getClinicId());
        dto.setConsult_type(tblBooking.getConsultType());
        dto.setAppointment_time(tblBooking.getAppointmentTime());
        dto.setTimezone(tblBooking.getBookingTimeZone());
        TblSpecialisation tblSpecialisation = new TblSpecialisation();
        tblSpecialisation.setIdentification(tblBooking.getSpecialisationId());
        List<TblSpecialisation> select = this.tblSpecialisationMapper.select(tblSpecialisation);
        TblSpecialisation tblSpecialisation1 = null;
        if(select != null && !select.isEmpty()) {
            tblSpecialisation1 = select.get(0);
        }
        if(StringUtil.isEmpty(tblBooking.getSpecialisationId())) {
            //GP
            dto.setService_type(1);
        }else if(tblSpecialisation1 != null) {
            if(tblSpecialisation1.getIdentificationGroup() != null) {
                if("2".equals(tblSpecialisation1.getIdentificationGroup()) ) {
                    // --Mental wellness
                    dto.setService_type(2);
                }else if("1".equals(tblSpecialisation1.getIdentificationGroup()) ) {
                    // --Paediatrician
                    dto.setService_type(3);
                }
            }
        }

        List<CancellationReasonVO> list =  this.tblBookingMapper.getAppointmentCancellationReasons(dto);
        return ResponseResultApp.success(list);
    }

    @Override
    public ResponseResultApp cancelAppointmentBooking(CancelAppointmentBookingDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        if(StringUtil.isEmpty(dto.getBooking_id())) {
            return ResponseResultApp.error("The booking_id field is required.");
        }
        if(StringUtil.isEmpty(dto.getReason_id())) {
            return ResponseResultApp.error("The reason_id field is required.");
        }
        //查询取消数据
        MemberCancelAppointmentVO memberCancelAppointmentVO = this.tblBookingMapper.getCancelAppointmentBooking(dto);
        if(memberCancelAppointmentVO == null) {
            return ResponseResultApp.error("The booking_id field is required.");
        }
        //查询取消理由
        TblAppointmentCancellationReason tblAppointmentCancellationReason = this.appointmentCancellationReasonMapper.selectByPrimaryKey(dto.getReason_id());
        if(tblAppointmentCancellationReason == null) {
            return ResponseResultApp.error("The reason_id field is required.");
        }
        String appointment_reason_text = tblAppointmentCancellationReason.getName();
        Integer reason_option_type = tblAppointmentCancellationReason.getOptionType();
        if(reason_option_type != null && reason_option_type == 2) {
            appointment_reason_text = dto.getReason_other_text();
        }
        if(appointment_reason_text == null) {
            appointment_reason_text = "";
        }

        MemberCancelAppointmentDto memberCancelAppointmentDto = new MemberCancelAppointmentDto();
        BeanUtils.copyProperties(memberCancelAppointmentVO, memberCancelAppointmentDto);
        memberCancelAppointmentDto.setAppointmentReasonText(appointment_reason_text);
        memberCancelAppointmentDto.setReasonOptionType(reason_option_type);
        memberCancelAppointmentDto.setBookingId(dto.getBooking_id());
        memberCancelAppointmentDto.setReasonId(dto.getReason_id());
        int i = this.tblBookingMapper.updateCancelAppointmentBooking(memberCancelAppointmentDto);
        //英文拼接的多个 可直接发送成功
        String appointmentEmail = memberCancelAppointmentVO.getAppointmentEmail();
        if (StringUtil.isEmpty(dto.getReason_id())) {
            try {
                String templateContent = HtmlUtils.getTemplateContent("EmailPatientCancelAppointment.ftl", null);

                //取消预约发送的邮件标题？  TODO
                String subject = "标题待定XXX" ;
                templateContent = templateContent.replace("[clinic_name]", memberCancelAppointmentVO.getClinicName());
                templateContent = templateContent.replace("[booking_code]", memberCancelAppointmentVO.getConsultationNo());

                templateContent = templateContent.replace("[doctor_name]", memberCancelAppointmentVO.getDoctorName());
                String appointmentCreatedOn = "";
                String appointment_start_time = "";
                String appointment_end_time = "";
                if(memberCancelAppointmentVO.getAppointmentCreatedOn() != null) {
                    appointmentCreatedOn = Kit.formatDateTime(memberCancelAppointmentVO.getAppointmentCreatedOn(),"yyyy-MM-dd HH:mm:ss");
                }
                if(memberCancelAppointmentVO.getAppointmentTime() != null) {
                    appointment_start_time = Kit.formatDateTime(memberCancelAppointmentVO.getAppointmentTime(),"yyyy-MM-dd HH:mm:ss");
                }
                if(memberCancelAppointmentVO.getAppointmentEndTime() != null) {
                    appointment_end_time = Kit.formatDateTime(memberCancelAppointmentVO.getAppointmentEndTime(),"yyyy-MM-dd HH:mm:ss");
                }
                templateContent = templateContent.replace("[appointment_date]", appointmentCreatedOn);
                templateContent = templateContent.replace("[appointment_start_time]", appointment_start_time);
                templateContent = templateContent.replace("[appointment_end_time]",appointment_end_time);
                templateContent = templateContent.replace("[cancellation_reason]", appointment_reason_text);


                String finalTemplateContent = templateContent;
                //异步处理邮件发送业务
                CompletableFuture.runAsync(() -> {
                    MailgunUtil.sendEmail(appointmentEmail, subject,null, finalTemplateContent);
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return ResponseResultApp.success();
    }

    @Override
    public ResponseResultApp setLabResultReminder(SetLabResultReminderDto dto) {

        TblLabResult tblLabResult = this.tblLabResultMapper.selectByPrimaryKey(dto.getLab_id());
        if(tblLabResult == null) {
            return ResponseResultApp.error("LabResult invalid");
        }
        TblBookingReminder tblBookingReminder = new TblBookingReminder();
        tblBookingReminder.setBookingId(tblLabResult.getBookingId());
        tblBookingReminder.setLabId(dto.getLab_id());
        tblBookingReminder.setMemId(tblLabResult.getMemId());
//        tblBookingReminder.setReminderValue();
//        tblBookingReminder.setReminderType();
//        //药品id 对应tbl_product
//        tblBookingReminder.setMedicationId();
        //原是当前时间加8小时
        tblBookingReminder.setReminderDate(Kit.plusHour(8,new Date()));
        String lab_results_setreminder_day = this.baseSysCodeService.getCodeValue("Lab_results_setreminder_day", null);
        //数据库默认值 3
        int lab_results_setreminder_day_int = 0;
        if(StringUtil.isNotEmpty(lab_results_setreminder_day)) {
            lab_results_setreminder_day_int = Integer.parseInt(lab_results_setreminder_day);
        }
        Integer unit = null;
        if(lab_results_setreminder_day_int > 0) {
            unit = 1;
        }
        tblBookingReminder.setRepeatDuration(lab_results_setreminder_day_int);
        tblBookingReminder.setRepeatDurationUnit(unit);
        tblBookingReminder.setProposedConsultationType(CoreAppConstants.ProposedConsultationType.LabResult.getValue());
        tblBookingReminder.setProposedConsultationStatus(1);
//        tblBookingReminder.setIsProposedConsultationStarted();
//        tblBookingReminder.setOriginalBookingId();
        int i = this.tblBookingReminderMapper.insertSelective(tblBookingReminder);
        String lab_results_setreminder_prompt_header = this.baseSysCodeService.getCodeValue("Lab_results_setreminder_prompt_header", null);
        String lab_results_setreminder_prompt_body = this.baseSysCodeService.getCodeValue("Lab_results_setreminder_prompt_body", null);
        if (i > 0)  {
            JSONObject objData = new JSONObject();
            objData.put("header_text",lab_results_setreminder_prompt_header);
            objData.put("message_text",lab_results_setreminder_prompt_body);
            return  ResponseResultApp.success(objData);

        }
        return ResponseResultApp.error("ErrorString.BAD_REQUEST");
    }

    @Override
    public ResponseResultApp shareLaboratoryResultViaEmail(ShareLaboratoryResultViaEmailDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        String account_id = curLoginMember.getId();
        TblLabResult tblLabResult = this.tblLabResultMapper.selectByPrimaryKey(dto.getLaboratoryId());
        if(tblLabResult == null) {
            return ResponseResultApp.error("LabResult invalid");
        }
        String memberEmail = curLoginMember.getEmail();
        String autoLabResultPdf = tblLabResult.getAutoLabResultPdf();
        String resultPdf1 = tblLabResult.getResultPdf();

        if (StringUtil.isNotEmpty(dto.getEmails())) {
            try {
                String fullName = curLoginMember.getFirstName();
                if(StringUtil.isNotEmpty(curLoginMember.getLastName())) {
                    fullName = fullName + " " + curLoginMember.getLastName();
                }
                String templateContent = HtmlUtils.getTemplateContent("SendDocument.ftl", null);
                templateContent = templateContent.replace("[Patient_Name]", fullName);
                String subject = "Whitecoat Laboratory Results: " + fullName;

                // because reuse template sendocument, but user want change text :))
                templateContent = templateContent.replace("Receive Teleconsult Session Document", "Access Laboratory Results");
                templateContent = templateContent.replace("[File_Name]", "Laboratory Results.pdf");
                templateContent = templateContent.replace("[Email]", memberEmail);
                templateContent = templateContent.replace("[Download_URL]", CoreAppConstants.APP_URL + "/v1/download/" + dto.getLaboratoryId());
                templateContent = templateContent.replace("[Current_Year]",Calendar.getInstance().get(Calendar.YEAR) + "" );
                //异步处理邮件发送业务
                String finalTemplateContent = templateContent;
                Map<String,String> map = new HashMap<>();
                map.put("laboratory.pdf", autoLabResultPdf);
                CompletableFuture.runAsync(() -> {
                    MailgunUtil.sendEmail(dto.getEmails(), subject,null, finalTemplateContent,map);
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseResultApp.success();
    }

    @Override
    public ResponseResultApp updateAllergiesAndMedicationReactions(UpdateAllergiesAndMedicationReactionsDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        TblMemberAllergies tblMemberAllergies = new TblMemberAllergies();
        tblMemberAllergies.setMemId(curLoginMember.getId());
        this.tblMemberAllergiesMapper.delete(tblMemberAllergies);
        List<UpdateAllergiesAndMedicationReactionsDto.Allergy> allergies = dto.getAllergies();
        // 2024-01-31  需求确认删除了 tbl_member_medication_reaction  及相关的逻辑 仅使用 tbl_member_allergies 表
        List<UpdateAllergiesAndMedicationReactionsDto.MedicationReaction> medication_reactions = dto.getMedication_reactions();
        List<TblMemberAllergies> tblMemberAllergiesList = new ArrayList<>();
        String producrIds = "";
        for (UpdateAllergiesAndMedicationReactionsDto.Allergy allergy :  allergies) {
            TblMemberAllergies a = new TblMemberAllergies();
            a.setId(IdUtil.fastUUID());
            a.setCreatedOnUtc(System.currentTimeMillis());
            a.setMemId(curLoginMember.getId());
            a.setMedicationReactionId(allergy.getId());
            producrIds = producrIds + allergy.getId() + ",";
            //a.setAllergiesName();
            tblMemberAllergiesList.add(a);
        }
        if(StringUtil.isNotEmpty(producrIds)) {
            List<Map<String,String>>  list = this.tblProductMapper.getIdAndName(Kit.getWhereByIds(producrIds));
            if(list != null && !list.isEmpty()) {
                for(Map<String,String> m : list) {
                    for (TblMemberAllergies a : tblMemberAllergiesList) {
                        if(m.get("id").equals(a.getMedicationReactionId())) {
                            a.setAllergiesName(m.get("name"));
                        }
                    }
                }
            }

        }
        this.tblMemberAllergiesMapper.insertList(tblMemberAllergiesList);
        //TODO 查询详情  字段需要哪些
        MemberInfoDetailVO memberInfoDetailVO = this.memberMapper.getMemberInfoDetailVO(curLoginMember.getId());
        if(memberInfoDetailVO != null) {
            String oldToken = JedisUtil.get(curLoginMember.getId(), CodeEnum.REDIS_USER.codeOf());
            memberInfoDetailVO.setAccessToken(oldToken);
        }
        return ResponseResultApp.success(memberInfoDetailVO);
    }

    @Override
    public ResponseResultApp removeSharedChild(RemoveSharedChildDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        //getChild_id  与前端老余确认过 就是用的memberId
        if(curLoginMember.getId().equals(dto.getChild_id())) {
            return ResponseResultApp.error("ErrorString.BAD_REQUEST");
        }
        TblMemberFamily memberFamily = new TblMemberFamily();
        memberFamily.setMemberId(curLoginMember.getId());
        memberFamily.setDependantId(dto.getChild_id());
        memberFamily.setDelFlag(0);
        List<TblMemberFamily> select = this.memberFamilyMapper.select(memberFamily);
        if(select == null || select.isEmpty()) {
            return ResponseResultApp.error("ErrorString.BAD_REQUEST");
        }
        TblMemberFamily tblMemberFamily = select.get(0);
        TblMemberFamily mf = new TblMemberFamily();
        mf.setId(tblMemberFamily.getId());
        mf.setDelFlag(0);
        this.memberFamilyMapper.updateByPrimaryKeySelective(mf);
        //removeChildBenefits  tbl_plan_benefit_member 该表删除 benefit 关系
        TblPlanBenefitMember tblPlanBenefitMember = new TblPlanBenefitMember();
        tblPlanBenefitMember.setDelFlag(1);
        tblPlanBenefitMember.setUpdatedBy(curLoginMember.getId());
        tblPlanBenefitMember.setUpdatedOnUtc(System.currentTimeMillis());
        Example example = new Example(TblPlanBenefitMember.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andCondition("mem_id = '"+dto.getChild_id()+"'");
        this.tblPlanBenefitMemberMapper.updateByExampleSelective(tblPlanBenefitMember,example);
        //TODO   addAllChildBenefitsIntoChild

        //TODO 更新成功返回一堆数据？用到了那些，那些是必要返回字段  前端实际没有使用 返回的data

        return ResponseResultApp.success("Your child\\u0027s personal information has been updated.",new JSONObject());

    }

    @Override
    public ResponseResultApp deleteChild(RemoveSharedChildDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        try {

            if(StringUtil.isEmpty(dto.getChild_id())) {
                return ResponseResultApp.error("Child invalid");
            }
            TblMember member = this.findEntityById(dto.getChild_id());
            if(member == null) {
                return ResponseResultApp.error("Child invalid");
            }

            String firstName = member.getFirstName();
            String lastName = member.getLastName();
            String FullName = firstName;
            if(StringUtil.isNotEmpty(lastName)) {
                FullName = FullName + lastName;
            }
            TblMemberFamily memberFamily = new TblMemberFamily();
            memberFamily.setDependantId(member.getId());
            memberFamily.setMemberId(curLoginMember.getId());
            memberFamily.setRelationship(0);
            memberFamily.setStatus(1);
            List<TblMemberFamily> select = this.memberFamilyMapper.select(memberFamily);
            if(select == null || select.isEmpty()) {
                return ResponseResultApp.error("CHILD_NOT_ACCESS");
            }
            TblBooking tblBooking = new TblBooking();
            tblBooking.setPatientMemId(dto.getChild_id());
            tblBooking.setDelFlag(0);
            int count = this.tblBookingMapper.selectCount(tblBooking);
            if(count > 0) {
                return ResponseResultApp.success("Sorry, we are unable to delete " + FullName + "’s profile as he / she has consulted with one of our doctors before.",null);
            }
            List<String> whereList = new ArrayList<>();
            whereList.clear();
            whereList.add("del_flag=0");
            whereList.add("id = '"+dto.getChild_id()+"'");
            whereList.add("parent_id = '"+curLoginMember.getId()+"'");
            TblMember tblMember = new TblMember();
            tblMember.setDelFlag(0);
            this.updateByEntity(tblMember,whereList);

        } catch (Exception ex) {
            log.error("DeleteChild: " + ex.getMessage());
            return ResponseResultApp.error();
        }
        MemberInfoDetailVO memberInfoDetailVO = this.memberMapper.getMemberInfoDetailVO(curLoginMember.getId());
        if(memberInfoDetailVO != null) {
            String oldToken = JedisUtil.get(curLoginMember.getId(), CodeEnum.REDIS_USER.codeOf());
            memberInfoDetailVO.setAccessToken(oldToken);
        }
        return ResponseResultApp.success(memberInfoDetailVO);
    }

    @Override
    public ResponseResultApp updateChildProfile(RemoveSharedChildDto dto) {
        String dateOfBirth = dto.getDateOfBirth();
        if(StringUtil.isEmpty(dateOfBirth)) {
            return ResponseResultApp.error("ErrorString.AGE_LESS_THAN_21");
        }
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        Date date = Kit.parseDateTimeStr(dateOfBirth, "yyyy-MM-dd");
        if(dto.getDateOfBirth() == null || Kit.getAge(date) > 16 || Kit.getAge(date) < 0) {
            return ResponseResultApp.error("ErrorString.AGE_LESS_THAN_21");
        }
        //TODO 需确认前端是否传这些参数
        String front_identification_card_photo_str = null;
        String back_identification_card_photo_str = null;
        String passport_photo_str = null;
        String certificate_photo_str = null;
        String child_photo_str = null;
        // general card
        String front_of_general_card_str = null;
        String back_of_general_card_str = null;
        int type;
        if (dto.getTypeId() == CoreAppConstants.MEMBER_TYPE_ID.NRIC_FIN) {
            type = 1;
        } else if (dto.getTypeId() == CoreAppConstants.MEMBER_TYPE_ID.PASSPORT) {
            type = 2;
        } else if (dto.getTypeId() == CoreAppConstants.MEMBER_TYPE_ID.BIRTH_CERTIFICATE) {
            type = 3;
        } else if (dto.getTypeId() == CoreAppConstants.MEMBER_TYPE_ID.DRIVING_LICENSE) {
            type = 4;
        } else if (dto.getTypeId() == CoreAppConstants.MEMBER_TYPE_ID.CHILD_PHOTO) {
            type = 5;
        } else {
            return ResponseResultApp.error("Mem type id invalid.");
        }
        List<String> whereList = new ArrayList<>();
        whereList.clear();
        whereList.add("del_flag=0");
        whereList.add("type = " + type);
        whereList.add("id='"+dto.getChild_id()+"'");
        TblMember oneByLimit = this.findOneByLimit(TblMember.class, whereList);
        if(oneByLimit == null) {
            return ResponseResultApp.error("ErrorString.CHILD_NOT_FOUND");
        }
        TblMemberFamily memberFamily = new TblMemberFamily();
        memberFamily.setDependantId(dto.getChild_id());
        memberFamily.setMemberId(curLoginMember.getId());
        memberFamily.setRelationship(0);
        memberFamily.setStatus(1);
        List<TblMemberFamily> select = this.memberFamilyMapper.select(memberFamily);
        if(select == null || select.isEmpty()) {
            return ResponseResultApp.error("ErrorString.CHILD_NOT_ACCESS");
        }
        if(StringUtil.isNotEmpty(dto.getNricFin())) {
            whereList.clear();
            whereList.add("del_flag=0");
            whereList.add("nric_fin = '"+dto.getNricFin()+"'");
            whereList.add("id!='"+dto.getChild_id()+"'");
            TblMember oneByLimit2 = this.findOneByLimit(TblMember.class, whereList);
            if(oneByLimit2 != null) {
                return ResponseResultApp.error("ErrorString.NRIC_HAS_BEEN_VERIFIED_CANNT_REMOVED");
            }
        }
        TblMember tblMemberUpdate = new TblMember();
        tblMemberUpdate.setId(dto.getChild_id());
        tblMemberUpdate.setFirstName(dto.getFirstName());
        tblMemberUpdate.setLastName(dto.getLastName());
        tblMemberUpdate.setType(type);
        tblMemberUpdate.setNricFin(dto.getNricFin());
        if("male".equals(dto.getGender())) {
            tblMemberUpdate.setGender(1);
        } else  if("female".equals(dto.getGender())) {
            tblMemberUpdate.setGender(0);
        }else{
            tblMemberUpdate.setGender(-1);
        }
        tblMemberUpdate.setDob(Kit.parseDateTimeStr(dto.getDateOfBirth(),"yyyy-MM-dd"));
        //父账号关系 1parent 2guardian 3mother 4father
        int relationship = 1;
        if("guardian".equals(dto.getGender())) {
            relationship = 2;
        } else  if("mother".equals(dto.getGender())) {
            relationship = 3;
        }else if("father".equals(dto.getGender())) {
            relationship = 4;
        }{
            tblMemberUpdate.setGender(-1);
        }
        tblMemberUpdate.setRelationship(relationship);
        //tblMemberUpdate.setFrontIdentificationCard();
        this.updateEntityById(tblMemberUpdate);
        MemberInfoDetailVO memberInfoDetailVO = this.memberMapper.getMemberInfoDetailVO(curLoginMember.getId());
        if(memberInfoDetailVO != null) {
            String oldToken = JedisUtil.get(curLoginMember.getId(), CodeEnum.REDIS_USER.codeOf());
            memberInfoDetailVO.setAccessToken(oldToken);
        }
        return ResponseResultApp.success(memberInfoDetailVO);



    }

    @Override
    public ResponseResultApp getConsultProfiles(ConsultProfilesDto dto) {
        TblMember curLoginMember = UserUtil.getCurLoginMember();
        curLoginMember = this.memberMapper.selectByPrimaryKey(curLoginMember.getId());
        String memberId = curLoginMember.getId();
        Integer service_type = dto.getService_type();
        if(StringUtil.isNotEmpty(dto.getChild_id())) {
            memberId = dto.getChild_id();
        }
        // 是否首次登录  ？？
        Date firstVisit = curLoginMember.getFirstVisit();
        boolean firstLogin = false;
        if(firstVisit != null) {
            firstLogin = true;
        }
        boolean isPIMUser =false;
        //TODO 不知道怎么来的
        //boolean isPIMUser = memberHelper.GetNumberOfPIMProfile(memberId) > 0;
        //service_type 0=GP;8 = Think well ;2 = Mental wellness;3 = Pead
        Integer[] serviceType = CoreAppConstants.SERVICE_TYPE;

        Map<String,String> serviceTypes = new HashMap<>();
        if(dto.getService_type() == 0) {
            for (Integer i : serviceType) {
                if(i != 3) {
                    serviceTypes.put(i.toString(),getServiceTypeName(i));
                }
            }
        }else {
            serviceTypes.put(dto.getService_type().toString(),getServiceTypeName(dto.getService_type()));
        }
        List<GetConsultProfilesVO> getConsultProfilesVOList = new ArrayList<>();
        //直接循环查询没有  根据每个service_type 下数据
        /*for (String s : serviceTypes.keySet()) {
            GetConsultProfilesVO getConsultProfilesVO = new GetConsultProfilesVO();
            getConsultProfilesVO.setServiceType(s);
            getConsultProfilesVO.setServiceName(serviceTypes.get(s));
            //根据每个service_type 查询 profileVO
            List<GetConsultProfileVo> consultProfileList = tblSupplierMapper.getConsultProfile(dto.getService_type(), memberId);
            getConsultProfilesVO.setProfiles(consultProfileList);
            getConsultProfilesVOList.add(getConsultProfilesVO);

        }*/
        //查询出所有Profile数据 优化 减少数据库查询   调用XuLinYu写好的公共部分代码 getConsultProfile   在getConsultProfile 方法中相同的调用
        List<GetConsultProfileVo> consultProfileList = tblSupplierMapper.getConsultProfile(null, memberId);
        Map<Integer, Integer> serviceTypeMap = new HashMap<>();
        if(consultProfileList != null && !consultProfileList.isEmpty()) {
            for (GetConsultProfileVo g : consultProfileList) {
                serviceTypeMap.put(g.getServiceType(), g.getServiceType());
            }
            //根据serviceType 归组数据
            for (Integer type : serviceTypeMap.keySet()) {
                List<GetConsultProfileVo> consultProfileList1 = new ArrayList<>();
                GetConsultProfilesVO getConsultProfilesVO = new GetConsultProfilesVO();
                getConsultProfilesVO.setServiceType(type.toString());
                getConsultProfilesVO.setServiceName(serviceTypes.get(type));
                for (GetConsultProfileVo g : consultProfileList) {
                    if(type.equals(g.getServiceType())) {
                        consultProfileList1.add(g);
                    }
                    serviceTypeMap.put(g.getServiceType(), g.getServiceType());
                }
                getConsultProfilesVO.setProfiles(consultProfileList1);
                getConsultProfilesVOList.add(getConsultProfilesVO);

            }
        }


        boolean can_show_tooltip = false;
        if (firstLogin){
            can_show_tooltip = true;
        }
        GetConsultProfilesResultVO getConsultProfilesResultVO = new GetConsultProfilesResultVO();
        getConsultProfilesResultVO.set_pim_user(isPIMUser);
        getConsultProfilesResultVO.setCan_show_tooltip(can_show_tooltip);
        getConsultProfilesResultVO.setGetConsultProfilesVOList(getConsultProfilesVOList);
        //没有数据数据参考，参考源码响应
        return ResponseResultApp.success(getConsultProfilesResultVO);
    }

    @Override
    @Transactional
    public ResponseResultApp deleteAccount(DeleteAccountDto dto) {
        //密码校验
        TblMember member = memberMapper.selectByPrimaryKey(UserUtil.getCurLoginUserId());
        String hash = PBKDF2Util.createHashPassword(dto.getPassword(),member.getIterationPassword(),member.getSaltPassword());
        // 校验登录密码
        if(!PBKDF2Util.verifyPassword(dto.getPassword(), member.getIterationPassword(), hash)) {
            //密码错误
            return ResponseResultApp.error("Wrong password");
        }
        //标记为锁定
        TblMember condition = new TblMember();
        condition.setLocked(1);
        condition.setLockedOn(new Date());
        condition.setId(member.getId());
        memberMapper.updateByPrimaryKeySelective(condition);

        //清除登录token
        String token = JedisUtil.get(member.getId(), CodeEnum.REDIS_USER.codeOf());
        if(StringUtils.isNotBlank(token)){
            JedisUtil.del(token,CodeEnum.REDIS_USER.codeOf());
        }
        JedisUtil.del(member.getId(),CodeEnum.REDIS_USER.codeOf());

        //构造内容发送邮件
        try {
            SysCode code = SysCodeUtil.getCode("Email_Ops_Team_Patient_Account_Deletion", "1");
            String toEmail = code.getValue().replaceAll("\\|", ",");
            Map<String,Object> data = new HashMap<>();
            data.put("PATIENT_FULL_NAME",(member.getFirstName()+" "+member.getLastName()).trim().toUpperCase());
            data.put("PATIENT_NRIC",member.getNricFin());
            data.put("PATIENT_NO",member.getMemberNo());
            String phone = member.getPhone();
            phone = "+" + tblCountryMapper.selectByPrimaryKey(member.getPhoneCountryId()).getDial()+" "+phone;
            data.put("PATIENT_MOBILE",phone);
            data.put("PATIENT_EMAIL",member.getEmail());
            String templateContent = HtmlUtils.getTemplateContent("Email_OPS_For_Account_Deletion.ftl", data);

            MailgunUtil.sendEmailAsync(toEmail,"User Account Deletion Request - "+data.get("PATIENT_FULL_NAME"),null,templateContent);

        }catch (Exception e){
            log.error("发送邮件异常",e);
        }

        return ResponseResultApp.success();
    }

    private String getServiceTypeName(Integer i) {
        //service_type 0=GP;8 = Think well ;2 = Mental wellness;3 = Pead
        String name = "";
        switch (i) {
            case 0:
                name = "GP";
                break;
            case 2:
                name = "Mental wellness";
                break;
            case 3:
                name = "Pead";
                break;
            case 8:
                name = "Think well";
                break;
        }
        return name;

    }

    /*@Override
    public ResponseResultApp getFamilyList(CommonDto dto) {
        dto.setId(UserUtil.getCurLoginMember().getId());
        FamilyAppVO familyAppVO = new FamilyAppVO();
        List<ChildVO> children = this.memberFamilyMapper.getChildrenList(dto);
        familyAppVO.setChildren(children);
        return ResponseResultApp.success(familyAppVO);
    }*/
}